﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace ReportGenerators.MuaHang
{
    public partial class FrmTongHopMuaHangTheoNCC_KCB : BasicForms.FrmSupportPrintableComponents
    {
        public FrmTongHopMuaHangTheoNCC_KCB()
        {
            InitializeComponent();
        }

        private void FrmThongKeMuaHang_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedIndex = 19;

                cmbKho.DataSource = GeneralLibs.SortDataAlphabetic.DataTableSort(DanhMucKho.Instance.DataTable, "Ten", 0).DefaultView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                cmbNCC.DataSource = GeneralLibs.SortDataAlphabetic.DataTableSort(DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView.ToTable(), "Ten", 0).DefaultView;
                cmbNCC.DisplayColumn = "Ten";
                cmbNCC.ValueColumn = "ID";
                cmbNCC.AddVisibleColumn("Ma", "Mã");
                cmbNCC.AddVisibleColumn("Ten", "Tên");

                gridControl.DataSource = dsThongKeMuaHang.Detail_ThongKeMuaHang;

                dsThongKeMuaHang.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataTable);
                dsThongKeMuaHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Instance.DataTable);    //Lấy tất cả các thuốc vì không dùng nhưng có thể đã mua

                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                }

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbNCC_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNCC.EditValue = Guid.Empty;
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (!(cmbNCC.EditValue is Guid) || (Guid)cmbNCC.EditValue == Guid.Empty)
            {
                FrmWarning.Show("Thông báo", "Chưa chọn nhà cung cấp!");
                cmbNCC.Focus();
                return;
            }

            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm \n" + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            BasicForms.FrmProgressBarDev.StartShowProgress();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                string nhaCungCapCondition = "1 = 1";
                nhaCungCapCondition = string.Format("B.DoiTuongNghiepVu1ID = '{0}'", cmbNCC.EditValue);

                string khoCondition = "1 = 1";
                if (cmbKho.EditValue != null && (Guid)cmbKho.EditValue != Guid.Empty) khoCondition = string.Format("B.Kho1ID = '{0}'", cmbKho.EditValue);

                cmd.CommandText = string.Format("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
                cmd.ExecuteNonQuery();

                cmd.CommandText = string.Format("SELECT D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh, SUM(C.Value1) SoLuong,  \n" +
                                               "   SUM(C.Value12*C.Value1)/SUM(C.Value1) GiaBia, SUM(C.Value13) ThanhTienGiaBia, SUM(C.Value8*C.Value1)/SUM(C.Value1) ChietKhau,  \n" +
                                               "   SUM(C.Value6*C.Value1)/SUM(C.Value1) GiaThanhToan, SUM(C.Value7) ThanhTien \n" +
                                               "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n" +
                                               "	INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n" +
                                               "	INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID  \n" +
                                               "	INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n" +
                                               "	LEFT JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                               "	INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID  \n" +
                                               "	INNER JOIN Kho ON B.Kho1ID = Kho.ID  \n" +
                                               "    LEFT JOIN PhuongThucThanhToanMuaHang PTBH ON A.PhuongThucThanhToanMuaBanHangID = PTBH.ID \n" +
                                               "WHERE LCT.Ma IN( 'HoaDonMuaHang' )      \n" +
                                               "	AND @ThoiDiemDau <= B.Ngay AND B.Ngay <= @ThoiDiemCuoi \n" +
                                               "	AND	{0} \n" +
                                               "	AND {1} \n" +
                                               "GROUP BY D.Ten, E.Ten, D.DonViTinh, C.Value12 ",
                                                nhaCungCapCondition, khoCondition);

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeMuaHang.Detail_ThongKeMuaHang.Clear();
                da.Fill(dsThongKeMuaHang.Detail_ThongKeMuaHang);

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("Failed to enable constraints"))
                    BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeader(true, gridControl, true, true, "Thống kê tổng hợp mua thuốc theo Nhà cung cấp", "");
        }
    }
}
